import { BaseModel } from '@/entity/base-model'
/**
 *
 *  将树形数据按照指定规则转换成一维数组
 * @param data 原数据
 * @param arr 转换容器数组(不用传)
 * @param rule 转换规则
 */
export function treeDataConverterOneArr(
  data: Array<any>,
  arr: Array<any> = [],
  rule: any = {
    label: 'name',
    value: 'id',
    children: 'children',
    parentId: 'parentId',
  },
): any {
  for (let parent of data) {
    let tempObj = {} as any
    Object.keys(rule).map((val: string) => {
      tempObj[val] = parent[rule[val]]
    })
    arr.push(tempObj)
    if (parent.children && parent.children.length > 0) {
      treeDataConverterOneArr(parent.children, arr, rule)
    }
  }
  // 清除所有子菜单数据
  arr.map((val) => (val.children = []))
  return arr
}

export interface TreeVo {
  label: string
  value: string
  children: Array<TreeVo>
  parentId: string
  [key: string]: any
}
/**
 * 将一维数组数据转换为树形数据
 * @param data 一维数组数据
 * @constructor
 */
export function OneArrToTree(data: Array<TreeVo>): Array<TreeVo> {
  // 获取首级列表
  const parent = data.filter((val) => !val.parentId || val.parentId == '' || val.parentId == '0')
  return buildTree(parent, data)
}

/**
 * 将数
 * @param list
 * @param result
 */
export function getListByChildren<T extends TreeProps>(list: Array<T>, result: Array<T>): Array<T> {
  result = result.concat(list)
  list.map((val) => {
    if (val.children && val.children.length > 0) {
      result = getListByChildren(val.children, result)
    }
  })
  return result.flat() as Array<T>
}

/**
 * 树型字段
 */
export interface TreeProps extends BaseModel {
  // 子节点类型
  children: Array<any>
}

/**
 * 构建树
 * @param parent 父节点
 * @param data 数据列表
 */
export function buildTree(parent: Array<TreeVo>, data: Array<TreeVo>): Array<TreeVo> {
  for (let first of parent) {
    for (let second of data) {
      if (first.value == second.parentId) {
        first.children = first.children.concat(second)
      }
    }
    if (first.children.length > 0) {
      buildTree(first.children, data)
    }
  }
  return parent
}
